package com.zmx.base.service;

import com.zmx.base.dto.BaseCommunityDto;
import com.zmx.base.entity.BaseCommunity;
import com.zmx.base.repository.BaseCommunityRepository;
import com.zmx.base.service.mapper.BaseCommunityMapper;
import com.zmx.common.common.service.BaseService;
import com.zmx.common.common.utils.Utils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author zhaomxr
 */
@Service
public class BaseCommunityService extends BaseService<BaseCommunity, BaseCommunityDto, BaseCommunityRepository, BaseCommunityMapper> {

    /**
     * 分页获取各区域
     * @param latitude
     * @param longitude
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Page getCommunityByPage(Double latitude, Double longitude, Integer pageIndex, Integer pageSize) {
        Map params = new HashMap<String, Object>(1);
        params.put("orders_sort", Sort.Direction.DESC);

        Page<BaseCommunityDto> page = this.getAll(params, pageIndex, pageSize);
        if (page.hasContent()) {
            for (BaseCommunityDto communityDto : page.getContent()) {
                String dimensionx = communityDto.getDimensionx();
                String dimensiony = communityDto.getDimensiony();
                if (latitude != null && longitude != null && !StringUtils.isEmpty(dimensionx) && !StringUtils.isEmpty(dimensiony)) {
                    Double distance = Utils.GetDistance(latitude, longitude, Double.valueOf(dimensionx), Double.valueOf(dimensiony));
                    communityDto.setDistance(distance);
                } else {
                    communityDto.setDistance(9999999D);
                }
            }
        }

        //根据distance进行升序排列（距离越近排名越靠前）
        Collections.sort(page.getContent(), new Comparator<BaseCommunityDto>() {
            public int compare(BaseCommunityDto o1, BaseCommunityDto o2) {
                return o1.getDistance().compareTo(o2.getDistance());
            }
        });

        return page;
    }
}
